package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOProperties;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleHtmlTasks {

    @Autowired
    private IApArticleContentService apArticleContentService;
    @Autowired
    private IApArticleService apArticleService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private MinIOProperties minIOProperties;

    @Async
    public void createArticleHtml(ApArticle apArticle, String content){
        try {
//        给指定的一个文章生成静态页面
        Long articleId= apArticle.getId();
//        1、获取准备好的模板
        Template template = configuration.getTemplate("article.ftl");
//        2、准备数据  Ap_article_content表中的content属性
        List<Map> mapList = mapList = JSON.parseArray(content, Map.class);

        Map dataModel = new HashMap();
        dataModel.put("content",mapList);
//                 3、结合后的页面
            StringWriter writer = new StringWriter();
            template.process(dataModel,writer);

        ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
//        4、上传到minio中
        minIOService.upload("/article/"+articleId+".html",inputStream,"text/html");//String name,InputStream inputStream,String contentType
        String staticUrl =  minIOProperties.getEndpoint()+"/"+minIOProperties.getBucketName()+"/article/"+articleId+".html";
        apArticle.setStaticUrl(staticUrl);
        apArticleService.updateById(apArticle);

        } catch (Exception e) {
            log.error("静态页面生成失败:"+apArticle.getId());
        }
    }


}
